﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.Threading;
using System.IO;
using System.Collections;

namespace 桌面视频录制
{
    public partial class FormCapture : Form
    {
        private VideoCapture videoCapture;
        private string savePath = String.Empty;//文件保存路径(含文件名)
        private int interval = 40;//录制时间间隔
        private Rectangle region = new Rectangle(0, 0, 500, 500);//录制区域
        private Point mouseDownPoint;
        private Bitmap backImage;
        private VideoPlay videoPlay;
        private string playFilePath = string.Empty;//播放文件路径
        private int playInterval = 40;//播放间隔时间
        private bool isSetRegion;
        private int recordTime;
        private int dw;
        private int dh;
        private int width;
        private int height;
        private double rate;
        private Rectangle selectedRegion = Rectangle.Empty;
        private bool isLocationChanged;
        private VideoProcess videoProcess;
        private List<DrawObject> drawObjectList = new List<DrawObject>();
        private List<DrawObject> selectedDrawObjectList = new List<DrawObject>();
        private DrawObject drawObject;
        private string selectedNodeText;
        private bool isMouseBusy;
        private bool isInControlRegion;
        private bool isBeginDrawRegion;
        private Rectangle partSelectedRegion = Rectangle.Empty;//局部选中的区域
        private FormTextInput textInput;
        private byte[] imageBytes;
        private bool startDrawPolygon;
        
        public FormCapture()
        {
            InitializeComponent();
        }

        private void trackBar1_Scroll(object sender, EventArgs e)
        {
            this.interval = trackBarRecord.Value;
            this.labelShowInterval.Text = trackBarRecord.Value.ToString();
            this.labelShowInterval.Refresh();
            if (videoCapture != null)
            {
                videoCapture.Interval = trackBarRecord.Value;
            }
        }

        private void buttonSetSavePath_Click(object sender, EventArgs e)
        {
            saveFileDialog.Filter = "(视频文件)*.xwc|*.xwc";
            saveFileDialog.FileName = DateTime.Now.ToString().Replace('/', '-').Replace(':', '-').Replace(' ', '@');
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                this.savePath = saveFileDialog.FileName;
                this.textBoxSavePath.Text = saveFileDialog.FileName;
            }
        }

        private void buttonRecord_Click(object sender, EventArgs e)
        {
            if (buttonRecord.Text == "开始录制")
            {
                if (savePath == string.Empty)
                {
                    MessageBox.Show("视频录制的保存路径未设置.");
                    return;
                }
                if (region.Width == 0 || region.Height == 0)
                {
                    MessageBox.Show("录制区域的宽或高不合法.");
                    return;
                }
                buttonRecord.Text = "停止录制";
                groupBoxPlay.Enabled = false;
                groupBoxVideoHandle.Enabled = false;
                buttonSetSavePath.Enabled = false;
                buttonSetRegion.Enabled = false;
                comboBox.Enabled = false;
                videoCapture = new VideoCapture(savePath, interval, region, comboBox.Text);
                videoCapture.Start();
                this.timer.Start();
            }
            else if (buttonRecord.Text == "停止录制")
            {
                buttonRecord.Text = "开始录制";
                groupBoxPlay.Enabled = true;
                groupBoxVideoHandle.Enabled = true;
                buttonSetSavePath.Enabled = true;
                buttonSetRegion.Enabled = true;
                comboBox.Enabled = true;
                videoCapture.Stop();
                videoCapture = null;
                this.timer.Stop();
                this.labelRecordTime.Text = "已录制:0秒";
                this.recordTime = 0;
            }
            else if (buttonRecord.Text == "暂停中..")
            {
                buttonRecord.Text = "停止录制";
                videoCapture.Start();
                this.timer.Start();
            }
        }

        private void buttonSetRegion_Click(object sender, EventArgs e)
        {
            buttonSetRegion.Enabled = false;
            this.isSetRegion = true;
            int width1 = SystemInformation.VirtualScreen.Width;
            int height1 = SystemInformation.VirtualScreen.Height;
            Bitmap image = new Bitmap(width1, height1);
            using (Graphics g = Graphics.FromImage(image))
            {
                g.CopyFromScreen(new Point(0, 0), new Point(0, 0), new Size(width1, height1));
            }
            this.backImage = image;
            DrawImage(backImage);
        }

        private void DrawImageOnPanel(Bitmap image)
        {
            DrawImage(image);
            image.Dispose();
            image = null;
        }

        private void DrawImage(Bitmap image)
        {
            int dw = 0;
            int dh = 0;
            int width = panelShow.Width;
            int height = panelShow.Height;
            if (1.0 * panelShow.Width / panelShow.Height > 1.0 * image.Width / image.Height)
            {
                width = image.Width * panelShow.Height / image.Height;
                dw = (panelShow.Width - width) / 2;
            }
            else
            {
                height = image.Height * panelShow.Width / image.Width;
                dh = (panelShow.Height - height) / 2;
            }
            //下面的方法可以避免画面的闪烁
            Graphics gg = panelShow.CreateGraphics();
            gg.SmoothingMode = SmoothingMode.AntiAlias;
            Bitmap canvas = new Bitmap(panelShow.Width, panelShow.Height);//创建一块画布
            using (Graphics graphics = Graphics.FromImage(canvas))
            {
                graphics.SmoothingMode = SmoothingMode.AntiAlias;
                graphics.Clear(Color.Black);
                graphics.DrawImage(image, dw, dh, width, height);//将图像绘制在画布上  
                if (buttonStartProcess.Text == "结束处理")
                {
                    foreach (DrawObject drawObject in drawObjectList)
                    {
                        drawObject.Draw(graphics);
                    }
                    foreach (DrawObject drawObject in selectedDrawObjectList)
                    {
                        drawObject.DrawControlPoint(graphics);
                    }
                    if (isBeginDrawRegion)
                    {
                        graphics.DrawRectangle(Pens.Red, partSelectedRegion);
                    }
                }
            }
            gg.DrawImage(canvas, 0, 0);//将画布绘制在Panel上
            canvas.Dispose();
            gg.Dispose();
            gg = null;;
        }
        private void panelShow_MouseDown(object sender, MouseEventArgs e)
        {
            this.mouseDownPoint = e.Location;
            if (e.Button == MouseButtons.Left && isSetRegion == true)
            {
                dw = 0;
                dh = 0;
                width = panelShow.Width;
                height = panelShow.Height;
                if (1.0 * panelShow.Width / panelShow.Height > 1.0 * backImage.Width / backImage.Height)
                {
                    width = backImage.Width * panelShow.Height / backImage.Height;
                    dw = (panelShow.Width - width) / 2;
                }
                else
                {
                    height = backImage.Height * panelShow.Width / backImage.Width;
                    dh = (panelShow.Height - height) / 2;
                }
                rate = 1.0 * SystemInformation.VirtualScreen.Width / width;

                Point relativePoint = new Point((int)((e.X - dw) * rate), (int)((e.Y - dh) * rate));//计算出实际桌面对应坐标
                this.labelStartPoint.Text = "(" + relativePoint.X + "," + relativePoint.Y + ")";
                this.labelStartPoint.Refresh();
            }
            if (e.Button == MouseButtons.Left && buttonStartProcess.Text == "结束处理")
            {
                if (selectedNodeText != "修改")
                {
                    if (selectedNodeText == "文本")
                    {
                        if (textInput != null && textInput.GetText() != "")
                        {
                            drawObject = new DrawText(e.Location, textInput.GetText(), textInput.GetTextFont());
                            drawObject.MouseDownPoint = e.Location;
                            drawObject.PenColor = this.textBoxSetColor.BackColor;
                            drawObject.PenWidth = float.Parse(comboBoxPenWidth.SelectedItem.ToString());
                            drawObjectList.Add(drawObject);
                        }
                        else
                        {
                            drawObject = null;
                            return;
                        }
                    }
                    else if (selectedNodeText == "图片")
                    {
                        if (imageBytes != null)
                        {
                            drawObject = new DrawImage(imageBytes, e.Location);
                            drawObject.MouseDownPoint = e.Location;
                            drawObject.PenColor = this.textBoxSetColor.BackColor;
                            drawObject.PenWidth = float.Parse(comboBoxPenWidth.SelectedItem.ToString());
                            drawObjectList.Add(drawObject);
                        }
                        else
                        {
                            drawObject = null;
                            return;
                        }
                    }
                    else if (selectedNodeText == "多边")
                    {
                        if (startDrawPolygon == false)
                        {
                            drawObject = new DrawPolygon(e.Location);
                            startDrawPolygon = true;
                            drawObject.MouseDownPoint = e.Location;
                            drawObject.PenColor = this.textBoxSetColor.BackColor;
                            drawObject.PenWidth = float.Parse(comboBoxPenWidth.SelectedItem.ToString());
                            drawObjectList.Add(drawObject);
                        }
                        else
                        {
                            DrawPolygon drawPolygon = drawObject as DrawPolygon;
                            if (drawPolygon != null)
                            {
                                drawPolygon.PointList.Add(e.Location);
                            }
                            else
                            {
                                this.startDrawPolygon = false;
                                return;
                            }
                        }
                    }
                    else if (selectedNodeText == "实多")
                    {
                        if (startDrawPolygon == false)
                        {
                            drawObject = new DrawPolygonWithFill(e.Location);
                            startDrawPolygon = true;
                            drawObject.MouseDownPoint = e.Location;
                            drawObject.PenColor = this.textBoxSetColor.BackColor;
                            drawObject.PenWidth = float.Parse(comboBoxPenWidth.SelectedItem.ToString());
                            drawObjectList.Add(drawObject);
                        }
                        else
                        {
                            DrawPolygon drawPolygon = drawObject as DrawPolygonWithFill;
                            if (drawPolygon != null)
                            {
                                drawPolygon.PointList.Add(e.Location);
                            }
                            else
                            {
                                this.startDrawPolygon = false;
                                return;
                            }
                        }
                    }
                    else
                    {
                        drawObject = videoProcess.GetDrawObject(selectedNodeText, e);
                        drawObject.MouseDownPoint = e.Location;
                        drawObject.PenColor = this.textBoxSetColor.BackColor;
                        drawObject.PenWidth = float.Parse(comboBoxPenWidth.SelectedItem.ToString());
                        drawObjectList.Add(drawObject);
                    }
                    
                }
                else
                {
                    if (buttonStartPoint.Enabled == false)
                    {
                        textBoxStartPoint.Text = e.X + "," + e.Y;
                        buttonStartPoint.Enabled = true;
                    }
                    if (buttonEndPoint.Enabled == false)
                    {
                        textBoxEndPoint.Text = e.X + "," + e.Y;
                        buttonEndPoint.Enabled = true;
                    }
                    if (buttonCenterPoint.Enabled == false)
                    {
                        textBoxCenterPoint.Text = e.X + "," + e.Y;
                        buttonCenterPoint.Enabled = true;
                    }

                    if (isInControlRegion == false)
                    {
                        bool isExit = false;
                        foreach (DrawObject drawObject in drawObjectList)
                        {
                            if (drawObject.JudgeIsSelected(e) == true)
                            {
                                selectedDrawObjectList.Clear();
                                selectedDrawObjectList.Insert(0, drawObject);
                                this.Cursor = Cursors.Hand;
                                this.isMouseBusy = true;
                                isExit = true;
                            }
                        }
                        if (!isExit)
                        {
                            if (selectedDrawObjectList.Count < 2)
                            {
                                this.isBeginDrawRegion = true;
                                this.isMouseBusy = true;
                            }
                            else
                            {
                                foreach (DrawObject drawObject in selectedDrawObjectList)
                                {
                                    drawObject.MouseDownPoint = e.Location;
                                }
                            }
                            this.splitContainer3.Panel2Collapsed = true;
                        }
                        else
                        {
                            Type type = selectedDrawObjectList[0].GetType();
                            if (type == typeof(DrawRectangleWithFill) || type == typeof(DrawEllipseWithFill) || type == typeof(DrawPolygonWithFill) || type == typeof(DrawParallelogramWithFill) || type == typeof(DrawClosedCurveWithFill) || type == typeof(DrawArcWithFill) || type == typeof(DrawText))
                            {
                                this.splitContainer3.Panel2Collapsed = false;
                            }
                            else
                            {
                                this.splitContainer3.Panel2Collapsed = true;
                            }
                        }
                    }
                    else
                        this.isMouseBusy = true;
                    if (selectedDrawObjectList.Count > 0)
                        selectedDrawObjectList[0].MouseDownPoint = e.Location;
                }
                DrawImage(videoProcess.ProcessImage);
            }
            if (e.Button == MouseButtons.Right && buttonStartProcess.Text == "结束处理")
            {
                if (selectedNodeText == "多边")
                {
                    DrawPolygon drawPolygon = drawObject as DrawPolygon;
                    if (drawPolygon != null && drawPolygon.PointList.Count > 2)
                    {
                        this.startDrawPolygon = false;
                        ((DrawPolygon)drawObject).StartDrawPolygon = true;
                    }
                }
                if (selectedNodeText == "实多")
                {
                    DrawPolygon drawPolygon = drawObject as DrawPolygonWithFill;
                    if (drawPolygon != null && drawPolygon.PointList.Count > 2)
                    {
                        this.startDrawPolygon = false;
                        ((DrawPolygonWithFill)drawObject).StartDrawPolygon = true;
                    }
                }
                DrawImage(videoProcess.ProcessImage);
            }
        }

        private void panelShow_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left && isSetRegion == true)
            {
                if (e.X > mouseDownPoint.X && e.Y > mouseDownPoint.Y)//4
                {
                    this.selectedRegion.Location = mouseDownPoint;
                    this.selectedRegion.Width = e.X - selectedRegion.X;
                    this.selectedRegion.Height = e.Y - selectedRegion.Y;
                }
                else if (e.X < mouseDownPoint.X && e.Y < mouseDownPoint.Y)//2
                {
                    this.selectedRegion.Location = e.Location;
                    this.selectedRegion.Width = mouseDownPoint.X - selectedRegion.X;
                    this.selectedRegion.Height = mouseDownPoint.Y - selectedRegion.Y;
                }
                else if (e.X > mouseDownPoint.X && e.Y < mouseDownPoint.Y)//1
                {
                    this.selectedRegion.X = mouseDownPoint.X;
                    this.selectedRegion.Y = e.Y;
                    this.selectedRegion.Width = e.X - selectedRegion.X;
                    this.selectedRegion.Height = mouseDownPoint.Y - selectedRegion.Y;
                }
                else//3
                {
                    this.selectedRegion.X = e.X;
                    this.selectedRegion.Y = mouseDownPoint.Y;
                    this.selectedRegion.Width = mouseDownPoint.X - selectedRegion.X;
                    this.selectedRegion.Height = e.Y - selectedRegion.Y;
                }
                Point relativePoint = new Point((int)((selectedRegion.X - dw) * rate), (int)((selectedRegion.Y - dh) * rate));//计算出实际桌面对应坐标
                region.Location = relativePoint;
                region.Width = (int)(Math.Abs(rate * selectedRegion.Width));
                region.Height = (int)(Math.Abs(rate * selectedRegion.Height));

                this.labelStartPoint.Text = "(" + region.X + "," + region.Y + ")";
                this.labelStartPoint.Refresh();
                this.labelWidthAndHeight.Text = "[" + region.Width + "," + region.Height + "]";
                this.labelWidthAndHeight.Refresh();
                ShowSelectedRegion(e, width, height);
            }
            else if (e.Button == MouseButtons.Left && isSetRegion == false && buttonStartProcess.Text != "结束处理")
            {
                this.Location = new Point(this.Location.X + (e.X - mouseDownPoint.X), this.Location.Y + (e.Y - mouseDownPoint.Y));
            }
            if (e.Button == MouseButtons.Left && buttonStartProcess.Text == "结束处理")
            {
                if (selectedNodeText != "修改" && drawObject != null)
                    drawObject.MouseMove(e);
                else
                {
                    if (selectedDrawObjectList.Count == 1)
                    {
                        if (isInControlRegion == false && this.Cursor == Cursors.Hand)
                        {
                            selectedDrawObjectList[0].MoveLocation(e);
                        }
                        if (isInControlRegion)
                        {
                            selectedDrawObjectList[0].ChangeSize(e);
                        }
                    }
                    if (isBeginDrawRegion)
                    {
                        if (e.X > mouseDownPoint.X && e.Y > mouseDownPoint.Y)//4
                        {
                            this.partSelectedRegion.Location = mouseDownPoint;
                            this.partSelectedRegion.Width = e.X - partSelectedRegion.X;
                            this.partSelectedRegion.Height = e.Y - partSelectedRegion.Y;
                        }
                        else if (e.X < mouseDownPoint.X && e.Y < mouseDownPoint.Y)//2
                        {
                            this.partSelectedRegion.Location = e.Location;
                            this.partSelectedRegion.Width = mouseDownPoint.X - partSelectedRegion.X;
                            this.partSelectedRegion.Height = mouseDownPoint.Y - partSelectedRegion.Y;
                        }
                        else if (e.X > mouseDownPoint.X && e.Y < mouseDownPoint.Y)//1
                        {
                            this.partSelectedRegion.X = mouseDownPoint.X;
                            this.partSelectedRegion.Y = e.Y;
                            this.partSelectedRegion.Width = e.X - partSelectedRegion.X;
                            this.partSelectedRegion.Height = mouseDownPoint.Y - partSelectedRegion.Y;
                        }
                        else//3
                        {
                            this.partSelectedRegion.X = e.X;
                            this.partSelectedRegion.Y = mouseDownPoint.Y;
                            this.partSelectedRegion.Width = mouseDownPoint.X - partSelectedRegion.X;
                            this.partSelectedRegion.Height = e.Y - partSelectedRegion.Y;
                        }
                    }
                    if (selectedDrawObjectList.Count > 1)
                    {
                        foreach (DrawObject drawObj in selectedDrawObjectList)
                        {
                            drawObj.MoveLocation(e);
                        }
                    }
                }

                DrawImage(videoProcess.ProcessImage);
            }
            if (buttonStartProcess.Text == "结束处理" && selectedNodeText == "修改")
            {
                //判断鼠标是否进入图形的控制点区域
                if (selectedDrawObjectList.Count > 0)
                {
                    if (isMouseBusy == false)
                    {
                        isInControlRegion = selectedDrawObjectList[0].JudgeIsInControlRegion(e);
                        if (isInControlRegion)
                            this.Cursor = Cursors.SizeAll;
                        else
                            this.Cursor = Cursors.Default;
                    }
                }
            }
        }

        private void ShowSelectedRegion(MouseEventArgs e, int width, int height)
        {
            using (Graphics gg = panelShow.CreateGraphics())
            {
                using (Bitmap canvas = new Bitmap(panelShow.Width, panelShow.Height))
                {
                    using (Graphics g = Graphics.FromImage(canvas))
                    {
                        g.Clear(Color.Black);
                        g.SmoothingMode = SmoothingMode.AntiAlias;
                        g.DrawImage(backImage, (panelShow.Width - width) / 2, (panelShow.Height - height) / 2, width, height);
                        g.DrawRectangle(Pens.Red, selectedRegion);
                    }
                    gg.SmoothingMode = SmoothingMode.AntiAlias;
                    gg.DrawImage(canvas, 0, 0);
                }
            }
        }

        private void panelShow_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left && (buttonSetRegion.Enabled == false || isSetRegion == true))
            {
                buttonSetRegion.Enabled = true;
                this.isSetRegion = false;
                if (backImage != null)
                {
                    backImage.Dispose();
                    backImage = null;
                }
            }
            if (isLocationChanged)
                isLocationChanged = false;
            if (e.Button == MouseButtons.Left && buttonStartProcess.Text == "结束处理" && selectedNodeText == "修改")
            {
                this.isMouseBusy = false;
                this.Cursor = Cursors.Default;
                if (isBeginDrawRegion)
                { 
                    Region region = new Region(partSelectedRegion);
                    selectedDrawObjectList.Clear();
                    foreach (DrawObject drawObject in drawObjectList)
                    {
                        if (drawObject.IsAllInRectangle(region))
                        {
                           this.selectedDrawObjectList.Add(drawObject);
                        }
                    }
                    region.Dispose();
                    this.isBeginDrawRegion = false;  
                    this.partSelectedRegion = Rectangle.Empty;
                    DrawImage(videoProcess.ProcessImage);
                }
                
            }
        }

        private void FormCapture_Load(object sender, EventArgs e)
        {
            comboBox.SelectedIndex = 0;
            comboBoxPenWidth.SelectedIndex = 0;

            //comboBoxWrapMode加载Item
            string[] wrapModeNames = Enum.GetNames(typeof(WrapMode));
            comboBoxWrapMode.Items.AddRange(wrapModeNames);
            comboBoxWrapMode.SelectedIndex = 0;
            //comboBoxHatchStyle加载Item
            string[] hatchStyleNames = Enum.GetNames(typeof(HatchStyle));
            comboBoxHatchStyle.Items.AddRange(hatchStyleNames);
            comboBoxHatchStyle.SelectedIndex = 0;
        }

        private void buttonSelectFile_Click(object sender, EventArgs e)
        {
            openFileDialog.Filter = "(视频文件)*.xwc|*.xwc";
            openFileDialog.FileName = DateTime.Now.ToString().Replace('/', '-').Replace(':', '-').Replace(' ', '@');
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                this.playFilePath = openFileDialog.FileName;
                this.textBoxPlayFilePath.Text = openFileDialog.FileName;
            }
        }

        private void trackBarPlay_Scroll(object sender, EventArgs e)
        {
            this.playInterval = trackBarPlay.Value;
            this.labelPlayInterval.Text = trackBarPlay.Value.ToString();
            this.labelPlayInterval.Refresh();
            if (videoPlay != null)
            {
                videoPlay.Interval = trackBarPlay.Value;
            }
        }

        private void buttonPlay_Click(object sender, EventArgs e)
        {
            if (buttonPlay.Text == "开始播放")
            {
                if (playFilePath == string.Empty)
                {
                    MessageBox.Show("没有选择要播放的视频文件!");
                    return;
                }
                buttonPlay.Text = "停止播放";
                groupBoxRecord.Enabled = false;
                groupBoxVideoHandle.Enabled = false;
                buttonSelectFile.Enabled = false;
                this.Text = Path.GetFileNameWithoutExtension(playFilePath);
                DrawImageDelegate d = new DrawImageDelegate(DrawImageOnPanel);

                videoPlay = new VideoPlay(playFilePath, playInterval, d);
                videoPlay.PlayOver += new PlayOverDelegate(videoPlay_PlayOver);
                this.progressBar.Maximum = (int)videoPlay.TotalLength;
                this.panelShow.ContextMenuStrip = this.contextMenuStrip;
                videoPlay.Play();
            }
            else if (buttonPlay.Text == "停止播放")
            {
                buttonPlay.Text = "开始播放";
                groupBoxRecord.Enabled = true;
                groupBoxVideoHandle.Enabled = true;
                buttonSelectFile.Enabled = true;
                this.Text = "视频录制和播放";
                this.progressBar.Value = 0;
                this.progressBar.Maximum = 0;
                this.labelShowProcess.Text = "已播放:0%";
                videoPlay.Stop();
                videoPlay = null;
                this.panelShow.ContextMenuStrip = null;
            }
            else if (buttonPlay.Text == "暂停中..")
            {
                buttonPlay.Text = "停止播放";
                videoPlay.Play();
            }
        }
        private delegate void ButtonPlayDelegate();
        private void VideoPlay()
        {
            buttonPlay.PerformClick();
            MessageBox.Show("文件已经播放完!", "温馨提示!");
        }
        private void videoPlay_PlayOver()
        {
            buttonPlay.Invoke(new ButtonPlayDelegate(VideoPlay));
        }
        private void DrawImageOnPanel(Bitmap image, long playLength)
        {
            DrawImageOnPanel(image);
            labelShowProcess.Invoke(new ShowCompletionRateDelegate(ShowCompletionRate), playLength);
        }
        private delegate void ShowCompletionRateDelegate(long playLength);
        private void ShowCompletionRate(long playLength)
        {
            if (progressBar.Maximum == 0)
                progressBar.Maximum = (int)videoPlay.TotalLength;
            else
                this.progressBar.Value = (int)playLength;
            this.labelShowProcess.Text = "已播放:" + (playLength * 100 / videoPlay.TotalLength) + "%";
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            recordTime++;
            int minutes = recordTime / 60;
            int seconds = recordTime % 60;
            this.labelRecordTime.Text = "已录制: " + minutes + ":" + seconds;
        }

        private void 全屏播放ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (全屏播放ToolStripMenuItem.Text == "全屏播放")
            {
                全屏播放ToolStripMenuItem.Text = "退出全屏";
                this.splitContainer1.Panel2Collapsed = true;
                this.FormBorderStyle = FormBorderStyle.None;
                this.WindowState = FormWindowState.Maximized;
            }
            else
            {
                全屏播放ToolStripMenuItem.Text = "全屏播放";
                this.splitContainer1.Panel2Collapsed = false;
                this.FormBorderStyle = FormBorderStyle.Sizable;
                this.WindowState = FormWindowState.Normal;
            }
        }

        private void panelShow_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left && isLocationChanged == false)
            {
                if (buttonPlay.Text == "停止播放")
                {
                    buttonPlay.Text = "暂停中..";
                    videoPlay.Pause();
                }
                else if (buttonPlay.Text == "暂停中..")
                {
                    buttonPlay.Text = "停止播放";
                    videoPlay.Play();
                }
                if (buttonRecord.Text == "停止录制")
                {
                    buttonRecord.Text = "暂停中..";
                    videoCapture.Stop();
                    this.timer.Stop();
                }
                else if (buttonRecord.Text == "暂停中..")
                {
                    buttonRecord.Text = "停止录制";
                    videoCapture.Start();
                    this.timer.Start();
                }
            }
            if (e.Button == MouseButtons.Right && buttonStartProcess.Text == "结束处理")
            {
                if (selectedNodeText != "修改")
                    selectedNodeText = "修改";
                else
                {
                    if (treeViewGraphicElements.SelectedNode != null)
                        selectedNodeText = treeViewGraphicElements.SelectedNode.Text;
                    else
                        selectedNodeText = "直线";
                    selectedDrawObjectList.Clear();
                }
                textBoxDrawObject.Text = selectedNodeText;
                DrawImage(videoProcess.ProcessImage);
            }
        }

        private void FormCapture_LocationChanged(object sender, EventArgs e)
        {
            this.isLocationChanged = true;
        }

        private void panelShow_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                if (全屏播放ToolStripMenuItem.Text == "全屏播放")
                    this.splitContainer1.Panel2Collapsed = !this.splitContainer1.Panel2Collapsed;
            }
        }

        private void 退出程序ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void FormCapture_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (buttonRecord.Text != "开始录制")
            {
                if (MessageBox.Show("当前正在进行视频录制,确实要退出吗?", "温馨提示!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) != DialogResult.Yes)
                {
                    e.Cancel = true;
                }
            }
            if (buttonPlay.Text != "开始播放")
            {
                if (MessageBox.Show("当前正在进行视频播放,确实要退出吗?", "温馨提示!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) != DialogResult.Yes)
                {
                    e.Cancel = true;
                }
            }
        }
        //定位播放
        private void progressBar_MouseUp(object sender, MouseEventArgs e)
        {
            if (buttonPlay.Text != "开始播放")
            {
                long newPos = e.X * videoPlay.TotalLength / progressBar.Width;
                videoPlay.PlayFromSetPos(newPos);
            }
        }

        private void trackBarProcess_Scroll(object sender, EventArgs e)
        {
            this.labelSelectedFrame.Text = trackBarProcess.Value.ToString();
            this.labelSelectedFrame.Refresh();
            DrawSelectedFrame(trackBarProcess.Value);
        }

        private void DrawSelectedFrame(int value)
        {
            videoProcess.SetProcessImage(value);
            DrawImage(videoProcess.ProcessImage);
        }
        //上一帧  下一帧
        private void buttonLastFrame_Click(object sender, EventArgs e)
        {
            Button button = sender as Button;
            switch (button.Name)
            { 
                case "buttonLastFrame":
                    if (trackBarProcess.Value > 0)
                        trackBarProcess.Value -= 1;
                    break;
                case "buttonNextFrame":
                    if (trackBarProcess.Value < trackBarProcess.Maximum)
                        trackBarProcess.Value += 1;   
                    break;
            }
            this.labelSelectedFrame.Text = trackBarProcess.Value.ToString();
            this.labelSelectedFrame.Refresh();
            DrawSelectedFrame(trackBarProcess.Value);
        }
        //图片帧处理
        private void buttonOpenToolbar_Click(object sender, EventArgs e)
        {
            Button button = sender as Button;
            ProcessFrame processFrame = null;
            switch (button.Name)
            {
                case "buttonOpenToolbar":
                    this.splitContainer2.Panel1Collapsed = !this.splitContainer2.Panel1Collapsed;
                    break;
                case "buttonDeleteFrame":
                    processFrame = new ProcessFrame(panelShow.Size, drawObjectList, true);
                    if (videoProcess.ProcessFrame(processFrame))
                        drawObjectList = new List<DrawObject>();
                    DrawImage(videoProcess.ProcessImage);
                    break;
                case "buttonDeleteDrawObject":
                    foreach (DrawObject drawObject in selectedDrawObjectList)
                    {
                        drawObjectList.Remove(drawObject);
                    }
                    selectedDrawObjectList.Clear();
                    DrawImage(videoProcess.ProcessImage);
                    break;
                case "buttonSaveFrame":
                    processFrame = new ProcessFrame(panelShow.Size, drawObjectList, false);
                    if (videoProcess.ProcessFrame(processFrame))
                    {
                        drawObjectList = new List<DrawObject>();
                        selectedDrawObjectList.Clear();
                    }
                    DrawImage(videoProcess.ProcessImage);
                    break;
            }
        }

        private void buttonSelectProcessFile_Click(object sender, EventArgs e)
        {
            openFileDialog.Filter = "(视频文件)*.xwc|*.xwc";
            openFileDialog.FileName = DateTime.Now.ToString().Replace('/', '-').Replace(':', '-').Replace(' ', '@');
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                textBoxProcessFileName.Text = openFileDialog.FileName;
            }
        }

        private void buttonSetNewFileName_Click(object sender, EventArgs e)
        {
            saveFileDialog.Filter = "(视频文件)*.xwc|*.xwc";
            saveFileDialog.FileName = DateTime.Now.ToString().Replace('/', '-').Replace(':', '-').Replace(' ', '@');
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                textBoxSveFileName.Text = saveFileDialog.FileName;
            }
        }

        private void buttonStartProcess_Click(object sender, EventArgs e)
        {
            if (buttonStartProcess.Text == "开始处理")
            {
                if (textBoxProcessFileName.Text == "" || textBoxSveFileName.Text == "")
                {
                    MessageBox.Show("未选择要处理的视频文件或未设置处理文件保存路径");
                    return;
                }
                buttonStartProcess.Text = "结束处理";
                buttonSelectProcessFile.Enabled = false;
                buttonSetNewFileName.Enabled = false;
                groupBoxRecord.Enabled = false;
                groupBoxPlay.Enabled = false;
                groupBoxVideoProcess.Enabled = true;
                videoProcess = new VideoProcess(textBoxProcessFileName.Text, textBoxSveFileName.Text);
                groupBox15.Text = "共" + videoProcess.TotalLength + "帧";
                trackBarProcess.Maximum = (int)videoProcess.TotalLength - 1;
                this.selectedNodeText = "直线";
                drawObjectList.Clear();
                DrawSelectedFrame(0);
            }
            else
            {
                buttonStartProcess.Text = "开始处理";
                buttonSelectProcessFile.Enabled = true;
                buttonSetNewFileName.Enabled = true;
                groupBoxRecord.Enabled = true;
                groupBoxPlay.Enabled = true;
                groupBoxVideoProcess.Enabled = false;
                this.splitContainer2.Panel1Collapsed = true;
                this.Cursor = Cursors.WaitCursor;
                videoProcess.EndProcess();
                videoProcess = null;
                this.Cursor = Cursors.Default;
                MessageBox.Show("处理完毕!");
            }
        }

        private void treeViewGraphicElements_AfterSelect(object sender, TreeViewEventArgs e)
        {
            this.selectedNodeText = treeViewGraphicElements.SelectedNode.Text;
            textBoxDrawObject.Text = selectedNodeText;
        }

        private void comboBoxPenWidth_SelectedIndexChanged(object sender, EventArgs e)
        {
            foreach (DrawObject drawObject in selectedDrawObjectList)
            {
                drawObject.PenWidth = float.Parse(comboBoxPenWidth.SelectedItem.ToString());
            }
            if (videoProcess != null && videoProcess.ProcessImage != null)
                DrawImage(videoProcess.ProcessImage);
        }

        private void buttonSetColor_Click(object sender, EventArgs e)
        {
            if (colorDialog.ShowDialog() == DialogResult.OK)
            {
                this.textBoxSetColor.BackColor = colorDialog.Color;
                foreach (DrawObject drawObject in selectedDrawObjectList)
                {
                    drawObject.PenColor = colorDialog.Color;
                }
                DrawImage(videoProcess.ProcessImage);
            }
        }

        private void panelShow_Paint(object sender, PaintEventArgs e)
        {
            if (buttonStartProcess.Text == "结束处理")
            {
                DrawImage(videoProcess.ProcessImage);
            }
        }

        private void treeViewGraphicElements_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Node.Text == "文本")
            {
                if (textInput == null)
                {
                    textInput = new FormTextInput();
                    textInput.ShowDialog();
                }
                else
                {
                    textInput.ShowDialog();
                }
            }
            else if (e.Node.Text == "图片")
            {
                openFileDialog.Filter = "(图片文件)*.jpg;*.bmp;*.png;*.gif|*.jpg;*.bmp;*.png;*.gif";
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    using (Stream stream = openFileDialog.OpenFile())
                    {
                        imageBytes = new byte[stream.Length];
                        stream.Read(imageBytes, 0, (int)stream.Length);
                    }
                }
            }
        }

        private void buttonSolidOK_Click(object sender, EventArgs e)
        {
            if (selectedDrawObjectList[0] == null)
                return;
            Button button = sender as Button;
            string buttonName = button.Name;
            if (buttonName == "buttonSolidOK")
            {
                selectedDrawObjectList[0].DrawBrush = new SolidDrawBrush(textBoxSolidColor.BackColor);
            }
            else if (buttonName == "buttonLinearOK")
            {
                try
                {
                    string[] xy = textBoxStartPoint.Text.Split(',');
                    Point startPoint = new Point(int.Parse(xy[0]), int.Parse(xy[1]));
                    xy = textBoxEndPoint.Text.Split(',');
                    Point endPoint = new Point(int.Parse(xy[0]), int.Parse(xy[1]));
                    selectedDrawObjectList[0].DrawBrush = new LinearGradientDrawBrush(startPoint, endPoint, textBoxStartColor.BackColor, textBoxEndColor.BackColor);
                }
                catch (Exception ee)
                {
                    MessageBox.Show(ee.Message);
                    return;
                }
            }
            else if (buttonName == "buttonTextureOK")
            {
                try
                {
                    if (pictureBoxFillImage.Image == null)
                        return;
                    Bitmap image = null;
                    int width, height;
                    if (1.0 * pictureBoxFillImage.Image.Width / pictureBoxFillImage.Image.Height < 1.0 * panelShow.Width / panelShow.Height)
                    {
                        width = panelShow.Width;
                        height = pictureBoxFillImage.Image.Height * width / pictureBoxFillImage.Image.Width;
                    }
                    else
                    {
                        height = panelShow.Height;
                        width = pictureBoxFillImage.Image.Width * height / pictureBoxFillImage.Image.Height;
                    }
                    image = new Bitmap(pictureBoxFillImage.Image, width, height);
                    WrapMode wrapMode = (WrapMode)(Enum.Parse(typeof(WrapMode), comboBoxWrapMode.SelectedItem.ToString()));
                    selectedDrawObjectList[0].DrawBrush = new TextureDrawBrush(image, wrapMode, this.panelShow.ClientRectangle);
                }
                catch (Exception ee)
                {
                    MessageBox.Show(ee.Message);
                    return;
                }

            }
            else if (buttonName == "buttonHatchOK")
            {
                HatchStyle hatchStyle = (HatchStyle)(Enum.Parse(typeof(HatchStyle), comboBoxHatchStyle.SelectedItem.ToString()));
                selectedDrawObjectList[0].DrawBrush = new HatchDrawBrush(textBoxForeColor.BackColor, textBoxBackColor.BackColor, hatchStyle);
            }
            else if (buttonName == "buttonPathOK")
            {
                Point centerPoint = new Point();
                try
                {
                    string[] xy = textBoxCenterPoint.Text.Split(',');
                    centerPoint.X = int.Parse(xy[0]);
                    centerPoint.Y = int.Parse(xy[1]);
                }
                catch (Exception ee)
                {
                    MessageBox.Show(ee.Message);
                    return;
                }
                selectedDrawObjectList[0].DrawBrush = new PathGradientDrawBrush(selectedDrawObjectList[0].GetPoints(), centerPoint, textBoxCenterColor.BackColor, textBoxSurroundColor.BackColor);
            }
            DrawImage(videoProcess.ProcessImage);
        }

        private void buttonSetSolid_Click(object sender, EventArgs e)
        {
            if (colorDialog.ShowDialog() == DialogResult.OK)
            {
                Button button = sender as Button;
                string buttonName = button.Name;
                if (buttonName == "buttonSetSolid")
                {
                    textBoxSolidColor.BackColor = colorDialog.Color;
                }
                else if (buttonName == "buttonStartColor")
                {
                    textBoxStartColor.BackColor = colorDialog.Color;
                }
                else if (buttonName == "buttonEndColor")
                {
                    textBoxEndColor.BackColor = colorDialog.Color;
                }
                else if (buttonName == "buttonForeColor")
                {
                    textBoxForeColor.BackColor = colorDialog.Color;
                }
                else if (buttonName == "buttonBackColor")
                {
                    textBoxBackColor.BackColor = colorDialog.Color;
                }
                else if (buttonName == "buttonCenterColor")
                {
                    textBoxCenterColor.BackColor = colorDialog.Color;
                }
                else if (buttonName == "buttonSurroundColor")
                {
                    textBoxSurroundColor.BackColor = colorDialog.Color;
                }
            }
        }

        private void buttonCenterPoint_Click(object sender, EventArgs e)
        {
            Button button = sender as Button;
            string buttonName = button.Name;
            if (buttonName == "buttonStartPoint")
                this.buttonStartPoint.Enabled = false;
            else if (buttonName == "buttonEndPoint")
                buttonEndPoint.Enabled = false;
            else if (buttonName == "buttonCenterPoint")
                buttonCenterPoint.Enabled = false;
        }

        private void pictureBoxFillImage_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            openFileDialog.Filter = "(图像文件)*.jpg;*.bmp|*.jpg;*.bmp";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                if (this.pictureBoxFillImage.Image != null)
                {
                    this.pictureBoxFillImage.Image.Dispose();
                    this.pictureBoxFillImage.Image = Image.FromFile(openFileDialog.FileName);
                }
                else
                    this.pictureBoxFillImage.Image = Image.FromFile(openFileDialog.FileName);
            }
        }

        private void 在最前端ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (在最前端ToolStripMenuItem.Checked == false)
                this.TopMost = true;
            else
                this.TopMost = false;
            在最前端ToolStripMenuItem.Checked = !在最前端ToolStripMenuItem.Checked;
        }
    }
}